package com.shop.socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author Song Yinghui
 * @date 2019/12/13
 * @Version 1.0
 *
 *  基于 UDP 协议的 socket编程
 */
public class UdpServer {

    public void start() throws IOException {
        int count = 0;
        int port = 5556; //接收端口
        DatagramSocket udpSocket = new DatagramSocket(port);
        while (true){
            byte[] buff = new byte[1024];
            DatagramPacket  receivePacket = new DatagramPacket(buff,buff.length);
            System.out.println("server started, wait for connect ... ");
            udpSocket.receive(receivePacket);
            count++;
            String result = new String(receivePacket.getData(), 0,receivePacket.getLength(), StandardCharsets.UTF_8);
            System.out.println("This is "+count+" client send's message :"+result);

            InetAddress address = receivePacket.getAddress();
            System.out.println("client host:"+address.getHostAddress()+",client port :"+receivePacket.getPort());

            String backMessage = "I'm server , This is Server answer message !";
            DatagramPacket packet = new DatagramPacket(backMessage.getBytes(StandardCharsets.UTF_8),backMessage.getBytes().length,
                    InetAddress.getByName(address.getHostAddress()),receivePacket.getPort());
            udpSocket.send(packet);
        }
    }

    public static void main(String[] args) throws IOException {
        new UdpServer().start();
    }
}
